package com.authine.cloudpivot.ext.service.ipml;

import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.engine.api.facade.BizObjectFacade;
import com.authine.cloudpivot.engine.api.facade.UserFacade;
import com.authine.cloudpivot.engine.api.model.dto.SimpleMsgDTO;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.enums.type.IMMessageChannelType;
import com.authine.cloudpivot.engine.enums.type.IMMessageType;
import com.authine.cloudpivot.engine.service.impl.component.RuntimeMessageComponent;
import com.authine.cloudpivot.engine.service.message.IMessageService;
import com.authine.cloudpivot.foundation.orm.api.dml.JPANativeQuery;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;
import java.util.Map;

/**
 * 通知
 */
@Slf4j
@Service
public class SyncKeyProjectServiceImpl {

    private static final String SHEAM_CODE = "zdxmgzapb";

    @Autowired
    JPANativeQuery jpaNativeQuery;

    @Autowired
    private BizObjectFacade bizObjectFacade;

    @PersistenceContext
    private EntityManager entityManager;

    @Autowired
    private UserFacade userFacade;

    public void notice(Boolean isnotice){

        String title="超时提醒";


        String sql = "SELECT * FROM `iknn4_zdxmgzapb`";
//        String sql = "SELECT * FROM `iknn4_zdxmgzapb` where id = 'b13a0c089c014e4dab5ae95c025d48e9'";
        List<Map<String,Object>> list = jpaNativeQuery.getList(sql, null, null);
        if (CollectionUtils.isNotEmpty(list)){
            for (Map<String,Object> map : list){
                String id =(String) map.get("id");
                String createId =(String) map.get("creater");
                String nxrIds =(String) map.get("ndbmlxr");
                String instanceName =(String) map.get("xmmc");
                Boolean flag = true;
                Boolean thisWeek = false;
                if (StringUtils.isNotBlank(nxrIds)){
                    String[] nxrIdArr = nxrIds.split(";");
                    for (String nxrId : nxrIdArr){
                        String querySql = String.format("SELECT * FROM `iknn4_xmjdqkb` where parentId = '%s' and gjr like '%%%s%%' and  YEARWEEK(gjsj, 1) = YEARWEEK(CURDATE(), 1)",id,nxrId);
                        List<Map<String,Object>> list1 = jpaNativeQuery.getList(querySql, null, null);
                        if (CollectionUtils.isEmpty(list1)){
                            if (isnotice){
                                //通知
                            IMessageService messageService = RuntimeMessageComponent.getMessageService(IMMessageChannelType.DINGTALK.name());
                            UserModel user = userFacade.get(nxrId);
                            String cont="您的【%s】项目进度情况未填写，请及时处理！";
                            cont = String.format(cont,instanceName);
                            senDingTalkMessage(messageService,user,title,cont);
                            }
                            flag = false;
                        }else {
                            thisWeek = true;
                        }
                    }


                }
                BizObjectCreatedModel bizObject = bizObjectFacade.getBizObject(SHEAM_CODE, id);

                bizObject.put("isNotice",flag ? "是" :"否");
                bizObject.put("thisWeek",thisWeek ? "是" :"否");
                bizObjectFacade.saveBizObject(createId, bizObject, Boolean.TRUE);

            }
        }
    }

    @Transactional
    public void updateStatus(String objectId){
        String sql = String.format("SELECT * FROM `iknn4_zdxmgzapb` where id = '%s'",objectId );
        List<Map<String,Object>> list = jpaNativeQuery.getList(sql, null, null);
        if (CollectionUtils.isNotEmpty(list)){
            for (Map<String,Object> map : list){
                String id =(String) map.get("id");
                String createId =(String) map.get("creater");
                String nxrIds =(String) map.get("ndbmlxr");
                Boolean flag = true;
                Boolean thisWeek = false;
                if (StringUtils.isNotBlank(nxrIds)){
                    String[] nxrIdArr = nxrIds.split(";");
                    for (String nxrId : nxrIdArr){
                        String querySql = String.format("SELECT * FROM `iknn4_xmjdqkb` where parentId = '%s' and gjr like '%%%s%%' and  YEARWEEK(gjsj, 1) = YEARWEEK(CURDATE(), 1)",id,nxrId);
                        List<Map<String,Object>> list1 = jpaNativeQuery.getList(querySql, null, null);
                        if (CollectionUtils.isEmpty(list1)){
                            flag = false;
                        }else {
                            thisWeek = true;
                        }
                    }
                }
                if (flag){
                    BizObjectCreatedModel bizObject = bizObjectFacade.getBizObject(SHEAM_CODE, id);
                    bizObject.put("isNotice","是");
                    bizObjectFacade.saveBizObject(createId, bizObject, Boolean.TRUE);
                }
                if (thisWeek){
                    BizObjectCreatedModel bizObject = bizObjectFacade.getBizObject(SHEAM_CODE, id);
                    bizObject.put("thisWeek","是");
                    String newSQl = String.format("SELECT id,jdqk,LongText1723105434167 as wtkl FROM `iknn4_xmjdqkb` where parentId = '%s' order by gjsj desc limit 1",id);
                    List<Map<String,Object>> list1 = jpaNativeQuery.getList(newSQl, null, null);
                    if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(list1)){
                        bizObject.put("bzzxjd",list1.get(0).get("jdqk"));
                        bizObject.put("zxjdczwtykn",list1.get(0).get("wtkl"));
                        String zbId = (String) list1.get(0).get("id");
                        String fileSql = String.format("select * from h_biz_attachment where bizObjectId = '%s' and schemaCode = 'xmjdqkb'",zbId);
                        List<Map<String,Object>> list2 = jpaNativeQuery.getList(fileSql, null, null);
                        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(list2)){
                            for (Map<String,Object> files : list2){
                                String insertSql = String.format("INSERT INTO `h_biz_attachment` (`id`, `bizObjectId`, `bizPropertyCode`, `createdTime`, `creater`, `fileExtension`, `fileSize`, `base64ImageStr`, `mimeType`, `name`,  `refId`, `schemaCode`) VALUES ('%s', '%s', 'zxjdfj', NOW(), '%s', '%s', %s, NULL, '%s', '%s', '%s', 'zdxmgzapb')", UUID.fastUUID().toString(), id, createId, files.get("fileExtension"), files.get("fileSize"), files.get("mimeType"), files.get("name"), files.get("refId"));
                                Query nativeQuery = entityManager.createNativeQuery(insertSql);
                                nativeQuery.executeUpdate();
                            }
                        }
                    }
                    bizObjectFacade.saveBizObject(createId, bizObject, Boolean.TRUE);
                }
            }
        }
    }

    private void senDingTalkMessage(IMessageService messageService, UserModel user , String title, String content){

        if (org.apache.commons.lang3.StringUtils.isEmpty(user.getUserId())){
            log.warn("用户钉钉ID为空，不推送钉钉消息！");
            return;
        }

        SimpleMsgDTO dto = new SimpleMsgDTO();
        try {

            //钉钉userId
            dto.setReceivers(user.getUserId());
            dto.setContent(content);
            dto.setTitle(title);
            dto.setMessageType(IMMessageType.BUSINESS_REMIND);
            dto.setCorpId(user.getCorpId());
            messageService.sendSimpleTextMsg(dto);
        } catch (Exception e) {
            log.info("用户：{}-账号：{}，送消息内容：{}",user.getName(),user.getUsername(), JSONObject.toJSONString(dto));
            log.error("钉钉消息发送失败",e);
        }
    }
}
